/**
 * Created by raniys on 4/12/17.
 */

var commonConst = require('./common-const');
var commonSetting = require('./common-setting');
var http = require('http');

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        // named pipe
        return val;
    }

    if (port >= 0) {
        // port number
        return port;
    }

    return false;
}

var request = require('request').defaults({jar: true});//可以设置cookie

var httpHelper = {
    get: function (url, tokenId, callback) {
        var j = request.jar();
        var cookie = request.cookie(commonConst.WEB_SESSION_TAG + "=" + tokenId);
        j.setCookie(cookie, commonSetting.WEB_HTTP_URL);
        request({
            url: url,
            method: 'GET',
            encoding: null,//need binary data,not utf8 string
            jar: j
        }, function (err, httpResponse, body) {
            callback(err, httpResponse, body);
        })
    },

    post: function (url, params, tokenId, callback) {
        var j = request.jar();
        var cookie = request.cookie(commonConst.WEB_SESSION_TAG + "=" + tokenId);
        j.setCookie(cookie, commonSetting.WEB_HTTP_URL);
        request({
            url: url,
            form: params,
            method: 'POST',
            encoding: null,//need binary data,not utf8 string
            jar: j
        }, function (err, httpResponse, body) {
            callback(err, httpResponse, body);
        })
    }
};




function startServer(port, app){
    app.set('port', port);
    var server = http.createServer(app);
    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        // handle specific listen errors with friendly messages
        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' 绑定需要提升的权限');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' 端口被占用');
                process.exit(1);
                break;
            default:
                console.error('服务器错误' + error);
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
        console.info('启动服务器在 http://localhost:' + addr.port);
    }
}


module.exports = {
    normalizePort: normalizePort,
    startServer: startServer,
    httpHelper: httpHelper
};